package com.fl.nj.pool;

import com.fl.nj.config.DBConfig;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * 连接池管理类
 * 负责管理多个数据库连接池
 */
public class ConnectionPoolManager {
    private static final Map<String, DataSource> dataSourceMap = new HashMap<>();

    /**
     * 初始化数据库连接池
     * @param poolId 连接池ID
     * @param dbConfig 数据库配置信息
     */
    public static void initDataSource(String poolId, DBConfig dbConfig) {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dbConfig.getUrl());
        config.setUsername(dbConfig.getUsername());
        config.setPassword(dbConfig.getPassword());
        config.setDriverClassName(dbConfig.getDriverClassName());
        config.setMaximumPoolSize(dbConfig.getMaximumPoolSize());
        config.setMinimumIdle(dbConfig.getMinimumIdle());
        config.setConnectionTimeout(dbConfig.getConnectionTimeout());
        config.setIdleTimeout(dbConfig.getIdleTimeout());
        config.setMaxLifetime(dbConfig.getMaxLifetime());

        HikariDataSource dataSource = new HikariDataSource(config);
        dataSourceMap.put(poolId, dataSource);
    }

    /**
     * 从指定的连接池中获取数据库连接
     * @param poolId 连接池ID
     * @return 数据库连接
     * @throws SQLException 数据库连接异常
     */
    public static Connection getConnection(String poolId) throws SQLException {
        DataSource dataSource = dataSourceMap.get(poolId);
        if (dataSource == null) {
            throw new SQLException("数据源未初始化: " + poolId);
        }
        return dataSource.getConnection();
    }

    /**
     * 关闭指定的连接池
     * @param poolId 连接池ID
     */
    public static void closeDataSource(String poolId) {
        DataSource dataSource = dataSourceMap.remove(poolId);
        if (dataSource instanceof HikariDataSource) {
            ((HikariDataSource) dataSource).close();
        }
    }

    /**
     * 关闭所有连接池
     */
    public static void closeAllDataSources() {
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            DataSource dataSource = entry.getValue();
            if (dataSource instanceof HikariDataSource) {
                ((HikariDataSource) dataSource).close();
            }
        }
        dataSourceMap.clear();
    }
}